
//
//  TstAddressbookVC.swift
//  TstChat
//
//  Created by wanghui on 2018/5/10.
//  Copyright © 2018年 daerwei. All rights reserved.
//

import UIKit

private let addressbookCell = "tableviewcell"

class TstAddressbookVC: ChatBaseController {
    var msg:ChatMessage!
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), style: .plain)
        tableView.separatorStyle = .singleLine
        //        tableView.estimatedRowHeight = 44
//        tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(TstAddressbookCell.self, forCellReuseIdentifier: addressbookCell)
        tableView.rowHeight = 55
//        tableView.backgroundColor = RGBA(r: 241/255, g: 240/255, b: 245/255, a: 1)
//        tableView.tableFooterView = UIView(frame: CGRect.zero)
        
        //设置索引的字体颜色 (默认是蓝色)
        tableView.sectionIndexColor = UIColor.black.withAlphaComponent(0.6)   //可以改变索引字体的颜色
        
        return tableView
    }()
    
    lazy var tablefootview:UIView = {
        let tablefootview = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 55))
        return tablefootview
    }()
    
    lazy var bottomLabel: UILabel = {
        let label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 18)
        label.textColor = UIColor.lightGray
        label.backgroundColor = UIColor.white
        return label
    }()
    
    lazy var footviewlineview: UIView = {
        let footviewlineview = UIView()
        footviewlineview.backgroundColor = RGBA(r: 228/255, g: 226/255, b: 226/255, a: 1)
        return footviewlineview
    }()
    
    var contactList = [ChatContact]()
    var sectionsArray: [[ChatContact]] = [[ChatContact]]()
    var selectedList = [ChatContact]()
    private var keysArray:[String] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(tableView)
        let homepageview = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(buttonTap(button:)))
        
        let spacer = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        spacer.width = -20
        // 首页按钮设置成功
        self.navigationItem.leftBarButtonItems = [homepageview]
        
        tablefootview.addSubview(footviewlineview)
        tablefootview.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(footviewlineview.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        footviewlineview.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        if self.title != NSLocalizedString("选择联系人",comment:"选择联系人") {
            bottomLabel.text = NSLocalizedString("\(self.contactList.count)位联系人",comment:"\(self.contactList.count)位联系人")
            self.tableView.tableFooterView = tablefootview
        }
    }
    let service = ContactService()
    
    func loadData() {
        DispatchQueue.global().async {
            self.contactList = self.service.getContactList()
            if self.contactList.count > 0 {
                DispatchQueue.main.async {
                    if self.title != NSLocalizedString("选择联系人",comment:"选择联系人") {
                        self.bottomLabel.text = NSLocalizedString("\(self.contactList.count)位联系人",comment:"\(self.contactList.count)位联系人")
                    }
                    self.setSection()
                }
            }
        }
    }
    
    @objc func buttonTap(button:UIButton) {
        if self.title == NSLocalizedString("选择联系人",comment:"选择联系人") {
            self.navigationController?.popViewController(animated: true)
        }else {
            self.tabBarController?.navigationController?.popViewController(animated: true)
        }
    }
    
    func setSection(){
        UILocalizedIndexedCollation.getCurrentKeysAndObjectsData(needSortArray: contactList, collationStringSelector: #selector(getter: ChatContact.displayName)) { (dataArray,titleArray) in
            self.sectionsArray = dataArray
            self.keysArray    = titleArray
            self.tableView.reloadData()
        }
    }
}

extension TstAddressbookVC:UITableViewDataSource, UITableViewDelegate {
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: addressbookCell, for: indexPath) as! TstAddressbookCell
        let chatContact = sectionsArray[indexPath.section][indexPath.row]
        
        cell.selectionStyle = .none
        cell.nameLabel.text = chatContact.displayName
        cell.headimage.kf.setImage(with: Common.avatarUrl(chatContact.avatar ?? "") ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
        //            cell.tagbutton.isHidden = true
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return keysArray.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return keysArray[section]
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 23
    }
    
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keysArray
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        if index == 0{
            tableView.setContentOffset(CGPoint.zero, animated: false)
            return 0
        }
        return index
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionsArray.count == 0 {
            return 0
        }
        return sectionsArray[section].count
    }
    
    //Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if self.title == NSLocalizedString("选择联系人",comment:"选择联系人") {
            let sendVC = sendToVC()
            sendVC.msg = msg
            let session = sectionsArray[indexPath.section][indexPath.row]
            sendVC.sessionServerId = session.userId
            sendVC.chatcontact = session
            sendVC.type = 0 //
            
            sendVC.definesPresentationContext = true;
            sendVC.modalPresentationStyle = .overFullScreen
            sendVC.modalTransitionStyle = .crossDissolve
            self.present(sendVC, animated: true)
        }else {
            let session = sectionsArray[indexPath.section][indexPath.row]
            let chatvc = ChatVC()
            chatvc.title = session.displayName
            chatvc.chatType = ChatType.p2p
            chatvc.sessionServerId = session.userId
            chatvc.sessionName = session.displayName
            chatvc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(chatvc, animated: true)
        }
    }
}

